<template>
  <div class="header">
    <van-nav-bar
      title="OA审批"
      left-arrow
      :border="false"
      @click-left="onClickLeft"
    >
      <template #left>
        <img src="@/assets/approvals/black-left.png" class="black-left" />
      </template>
      <!-- <template #right>
        <img
          src="@/assets/approvals/search.png"
          class="search"
          @click="toggleSearch"
        />
      </template> -->
    </van-nav-bar>
    <div class="oa-tab">
      <div
        class="tab-li"
        v-for="(item, index) in tabList"
        :key="item.text"
        @click="changeTab(index)"
      >
        <!-- <div class="num" v-if="item.num">{{ item.num }}</div> -->
        <van-badge
          class="num"
          :content="item.num"
          max="10"
          v-if="parseInt(item.num) > 0"
        />
        <img :src="item.src" />
        <span>{{ item.text }}</span>
        <img
          v-if="index === tabIndex"
          class="tab-active"
          src="@/assets/approvals/tab-active.png"
        />
      </div>
    </div>
  </div>
  <div class="content">
    <!-- 搜索框 -->
    <div class="search-container">
      <search-input
        v-model="searchKeyword"
        :defaultValue="''"
        clearable
        @search="handleSearch"
        @clear="handleClear"
        autocomplete="off"
      />
    </div>

    <!-- 加载骨架屏 -->
    <div v-if="loading" class="approval-skeleton">
      <van-skeleton :row="8" :loading="true" />
    </div>

    <!-- 列表内容 -->
    <div v-else-if="dataList.length > 0" class="list-container">
      <div
        v-for="item in filteredDataList"
        :key="item.id"
        class="list-item"
        @click="handleItemClick(item)"
      >
        <!-- 标题和编号 -->
        <div class="item-header">
          <div class="item-title">{{ getApprovalTitle(item) }}</div>
          <div v-if="item.createDate" class="item-no">
            {{ item.createDate }}
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="item-details">
          <!-- 合同类型 -->
          <template v-if="item.type === '1'">
            <div v-if="item.name" class="detail-row">
              <span class="label">合同名称：</span>
              <span class="value">{{ item.name }}</span>
            </div>
            <div v-if="item.amountType" class="detail-row">
              <span class="label">金额类型：</span>
              <span class="value">{{
                getAmountTypeName(item.amountType)
              }}</span>
            </div>
            <div v-if="item.contractTermType" class="detail-row">
              <span class="label">合同期限：</span>
              <span class="value">{{
                getTermTypeName(item.contractTermType)
              }}</span>
            </div>
            <div v-if="item.ourEntityName" class="detail-row">
              <span class="label">我方主体名称：</span>
              <span class="value">{{ item.ourEntityName }}</span>
            </div>
            <div v-if="item.otherEntityName" class="detail-row">
              <span class="label">我方负责人：</span>
              <span class="value">{{ item.otherEntityName }}</span>
            </div>
          </template>

          <!-- 报销类型 -->
          <template v-else-if="item.type === '2'">
            <div v-if="item.amount" class="detail-row">
              <span class="label">报销金额：</span>
              <span class="value amount">{{ item.amount }}</span>
            </div>
            <div v-if="item.amountDate" class="detail-row">
              <span class="label">费用发生日期：</span>
              <span class="value"> {{ formatDateOnly(item.amountDate) }}</span>
            </div>

            <div v-if="item.amountType" class="detail-row">
              <span class="label">报销类型：</span>
              <span class="value">{{
                getExpenseTypeName(item.amountType)
              }}</span>
            </div>
            <div v-if="item.amountRemark" class="detail-row">
              <span class="label">报销明细：</span>
              <span class="value">{{ item.amountRemark }}</span>
            </div>
          </template>

          <!-- 付款类型 -->
          <template v-else-if="item.type === '3'">
               <div v-if="item.payDate" class="detail-row">
              <span class="label">付款日期：</span>
              <span class="value amount">{{formatDateOnly(item.payDate) }}</span>
            </div>
            <div v-if="item.payAmount" class="detail-row">
              <span class="label">付款金额：</span>
              <span class="value amount">{{ item.payAmount }}</span>
            </div>
              <div v-if="item.payObjectName" class="detail-row">
              <span class="label">付款对象：</span>
              <span class="value amount">{{ item.payObjectName }}</span>
            </div>
            <div v-if="item.payRemark" class="detail-row">
              <span class="label">付款说明：</span>
              <span class="value">{{ item.payRemark }}</span>
            </div>
          </template>
        </div>

        <!-- 通用信息 -->
        <!-- <div class="item-meta">
          <div class="meta-row">
            <span class="label">部门：</span>
            <span class="value">{{ item.department }}</span>
          </div>
          <div v-if="item.createDate" class="meta-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(item.createDate) }}</span>
          </div>
        </div> -->
        <!-- 当前审批人和状态标识 -->
        <div class="approval-status-row">
          <div class="approver-info">
            <div class="approver-avatar">
              <van-icon name="friends-o" class="approver-icon" />
            </div>
            <span class="approver-text">{{ item.createName }}</span>
          </div>
          <!-- 状态标识 -->
          <div class="status-badge" :class="getStatusClass(item)">
            {{ getStatusText(item) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-container">
      <img
        src="/src/assets/homeOther/empty.png"
        alt="暂无数据"
        class="empty-image"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import daichuli from "@/assets/approvals/daichuli.png";
import yichuli from "@/assets/approvals/yichuli.png";
import yifaqi from "@/assets/approvals/yifaqi.png";
import shoudaode from "@/assets/approvals/shoudaode.png";
import SearchInput from "@/components/SearchInput/index.vue";
import {
  getExpenseTypeName,
  getTermTypeName,
  getAmountTypeName,
} from "@/utils/enums";
import { formatDateUTC as formatDate, formatShortDateTime ,formatDateOnly} from '@/utils/formatters'
import {
  queryPendingApi,
  queryProcessedApi,
  queryInitiatedApi,
  queryReceivedApi,
} from "@/api/home";
import { TabItem, TabIndex } from "./index";

// 路由实例
const router = useRouter();
const route = useRoute();

// 响应式数据
const tabIndex = ref<TabIndex>(0);
const loading = ref(false); // 初始为false，避免闪烁
const showSearch = ref(false);
const searchKeyword = ref("");
const dataList = ref<any[]>([]);

// Tab配置
const tabList = ref<TabItem[]>([
  {
    src: daichuli,
    text: "待处理",
    num: "",
  },
  {
    src: yichuli,
    text: "已处理",
    num: "",
  },
  {
    src: yifaqi,
    text: "已发起",
    num: "",
  },
  {
    src: shoudaode,
    text: "我收到的",
    num: "",
  },
]);

// API映射
const apiMap = {
  0: queryPendingApi,
  1: queryProcessedApi,
  2: queryInitiatedApi,
  3: queryReceivedApi,
};

// 计算属性：过滤后的数据列表
const filteredDataList = computed(() => {
  // 确保searchKeyword是字符串类型
  const searchValue = String(searchKeyword.value || "").trim();
  if (!searchValue) {
    return dataList.value;
  }

  const keyword = searchValue.toLowerCase();
  console.log(keyword, "-keyword");
  return dataList.value.filter((item) => {
    // 基础字段搜索：名称、创建人、部门、标题
    const approvalTitle = getApprovalTitle(item).toLowerCase();
    const basicMatch =
      item.name?.toLowerCase().includes(keyword) ||
      item.createName?.toLowerCase().includes(keyword) ||
      item.department?.toLowerCase().includes(keyword) ||
      approvalTitle.includes(keyword);

    if (basicMatch) return true;

    // 根据类型进行特定字段搜索
    switch (item.type) {
      case "1": // 合同类型
        return (
          item.ourEntityName?.toLowerCase().includes(keyword) ||
          item.otherEntityName?.toLowerCase().includes(keyword) ||
          item.ourCharge?.toLowerCase().includes(keyword) ||
          item.otherCharge?.toLowerCase().includes(keyword) ||
          item.contractNote?.toLowerCase().includes(keyword) ||
          getTermTypeName(item.contractTermType)
            ?.toLowerCase()
            .includes(keyword) ||
          getAmountTypeName(item.amountType)?.toLowerCase().includes(keyword) ||
          item.signingMethod?.toLowerCase().includes(keyword) ||
          item.sealType?.toLowerCase().includes(keyword)
        );

      case "2": // 报销类型
        return (
          item.amount?.toString().includes(keyword) ||
          getExpenseTypeName(item.amountType)
            ?.toLowerCase()
            .includes(keyword) ||
          item.amountRemark?.toLowerCase().includes(keyword)
        );

      case "3": // 付款类型
        return (
          item.payAmount?.toString().includes(keyword) ||
          item.payRemark?.toLowerCase().includes(keyword) ||
          item.payObjectName?.toLowerCase().includes(keyword)
        );

      default:
        return false;
    }
  });
});

// 获取所有tab的统计数据
const fetchAllStatistics = async () => {
  try {
    // 并发请求所有统计数据
    const [pendingRes, processedRes, initiatedRes, receivedRes] =
      await Promise.all([
        queryPendingApi(),
        queryProcessedApi(),
        queryInitiatedApi(),
        queryReceivedApi(),
      ]);

    // 更新所有tab的数量显示
    if (pendingRes.code === 0) {
      const total = pendingRes.data.pendingTotal || 0;
      tabList.value[0].num = total > 99 ? "99+" : total.toString();
    }
    if (processedRes.code === 0) {
      const total = processedRes.data.processedTotal || 0;
      tabList.value[1].num = total > 99 ? "99+" : total.toString();
    }
    if (initiatedRes.code === 0) {
      const total = initiatedRes.data.initiatedTotal || 0;
      tabList.value[2].num = total > 99 ? "99+" : total.toString();
    }
    if (receivedRes.code === 0) {
      const total = receivedRes.data.receivedTotal || 0;
      tabList.value[3].num = total > 99 ? "99+" : total.toString();
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};

// 获取除当前tab外的其他tab统计数据
const fetchOtherTabsStatistics = async (currentTabIndex: number) => {
  try {
    const promises: { index: number; promise: Promise<any> }[] = [];
    const apiCalls = [queryPendingApi, queryProcessedApi, queryInitiatedApi, queryReceivedApi];
    
    // 只请求非当前tab的API
    for (let i = 0; i < apiCalls.length; i++) {
      if (i !== currentTabIndex) {
        promises.push({ index: i, promise: apiCalls[i]() });
      }
    }
    
    const results = await Promise.all(promises.map(item => item.promise));
    
    // 更新对应tab的数量显示
    results.forEach((response, idx) => {
      const tabIndex = promises[idx].index;
      if (response.code === 0) {
        const totalKey = ['pendingTotal', 'processedTotal', 'initiatedTotal', 'receivedTotal'][tabIndex];
        const total = response.data[totalKey] || 0;
        tabList.value[tabIndex].num = total > 99 ? "99+" : total.toString();
      }
    });
  } catch (error) {
    console.error("获取其他tab统计数据失败:", error);
  }
};

// 更新当前tab的统计数据
const updateCurrentTabStatistics = (response: any, tabIndex: number) => {
  if (response.code === 0) {
    const totalKeys = ['pendingTotal', 'processedTotal', 'initiatedTotal', 'receivedTotal'];
    const totalKey = totalKeys[tabIndex];
    const total = response.data[totalKey] || 0;
    tabList.value[tabIndex].num = total > 99 ? "99+" : total.toString();
  }
};

// 获取当前tab的数据
const fetchData = async () => {
  loading.value = true;
  try {
    const api = apiMap[tabIndex.value as keyof typeof apiMap];
    const response = await api();

    if (response.code === 0) {
      dataList.value = response.data.resultList || [];
      // 同时更新当前tab的统计数据
      updateCurrentTabStatistics(response, tabIndex.value);
    } else {
      showToast(response.msg || "获取数据失败");
      dataList.value = [];
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    showToast("获取数据失败");
    dataList.value = [];
  } finally {
    loading.value = false;
  }
};

// 切换Tab
const changeTab = async (index: TabIndex) => {
  tabIndex.value = index;

  // 更新URL参数，但不触发路由监听
  router.replace({
    path: route.path,
    query: {
      ...route.query,
      tab: index.toString(),
    },
  });

  // 获取当前tab数据和其他tab的badge数量，避免重复请求
  await Promise.all([
    fetchData(), // 这个会同时更新当前tab的统计数据
    fetchOtherTabsStatistics(index) // 只更新其他tab的统计数据
  ]);
};

// 返回上一页：统一返回到首页，避免回到详情造成循环
const onClickLeft = () => {
  router.push('/home');
};

// 切换搜索框显示
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
  if (!showSearch.value) {
    searchKeyword.value = "";
  }
};

// 处理搜索
const handleSearch = (value: string) => {
  searchKeyword.value = value;
};

// 清除搜索
const handleClear = () => {
  searchKeyword.value = "";
};

// 处理列表项点击
const handleItemClick = (item: any) => {
  // 根据类型跳转到对应的详情页面
  switch (item.type) {
    case "1": // 合同
      router.push({
        path: `/contract/detail/${item.id}`,
        query: { type: item.type, from: 'approvals' },
      });
      break;
    case "2": // 报销
      router.push({
        path: `/expense/detail/${item.id}`,
        query: { type: item.type, from: 'approvals' },
      });
      break;
    case "3": // 付款
      router.push({
        path: `/contract/detail/pay-detail/${item.id}`,
        query: { type: item.type, from: 'approvals' },
      });
      break;
    default:
      showToast("未知的类型");
  }
};

// 获取状态样式类
// 0是等待审批 1是审批完成 -1是已撤销 2是已拒绝
const getStatusClass = (item: any) => {
  const nowState = item.nowState;
  switch (nowState) {
    case 0:
      return "status-pending"; // 等待审批
    case 1:
      return "status-completed"; // 审批完成
    case -1:
      return "status-revoked"; // 已撤销
    case 2:
      return "status-rejected"; // 已拒绝
    default:
      return "status-unknown"; // 未知状态
  }
};
// 0是等待审批 1是审批完成  -1是已撤销 2是已拒绝
// 获取状态文本
const getStatusText = (item: any) => {
  const nowState = item.nowState;
  switch (nowState) {
    case 0:
      return "处理中";
    case 1:
      return "审批完成";
    case -1:
      return "已撤销";
    case 2:
      return "已拒绝";
    default:
      return null;
  }
};



// 获取审批标题（createName + type组合）
const getApprovalTitle = (item: any) => {
  const createName = item.createName || "未知用户";
  let typeText = "";

  switch (item.type) {
    case "1":
      typeText = "合同审批";
      break;
    case "2":
      typeText = "报销单据";
      break;
    case "3":
      typeText = "付款单据";
      break;
    default:
      typeText = "审批";
  }

  return `${createName}提交的${typeText}`;
};

// 标记是否为初始化阶段
const isInitializing = ref(true);

// 监听路由参数变化 - 仅在初始化时生效
watch(
  () => route.query.tab,
  (newTab) => {
    // 只在初始化阶段响应路由参数变化
    if (isInitializing.value && newTab !== undefined) {
      const tabIndexFromQuery = parseInt(newTab as string);
      if (
        !isNaN(tabIndexFromQuery) &&
        tabIndexFromQuery >= 0 &&
        tabIndexFromQuery < tabList.value.length
      ) {
        tabIndex.value = tabIndexFromQuery;
      }
    }
  },
  { immediate: true }
);

// 监听tabIndex变化，仅在初始化时自动获取数据
watch(
  tabIndex,
  () => {
    // 只在初始化阶段自动获取数据，避免与changeTab重复请求
    if (isInitializing.value) {
      fetchData();
    }
  },
  { immediate: true }
);

// 页面挂载时初始化
onMounted(async () => {
  // 优化加载体验：延迟显示loading，避免闪烁
  let loadingTimer: NodeJS.Timeout | null = null;
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    loading.value = true;
  }, 200);
  
  try {
    // 从路由参数获取初始tab
    const tabFromQuery = route.query.tab;
    if (tabFromQuery) {
      const tabIndexFromQuery = parseInt(tabFromQuery as string);
      if (
        !isNaN(tabIndexFromQuery) &&
        tabIndexFromQuery >= 0 &&
        tabIndexFromQuery < tabList.value.length
      ) {
        tabIndex.value = tabIndexFromQuery;
      }
    }

    // 总是请求最新的统计数据，确保数据实时性
    await fetchAllStatistics();

    // 初始化完成，后续不再响应路由参数变化
    isInitializing.value = false;
  } finally {
    // 数据加载完成后清除定时器和loading状态
    if (loadingTimer) {
      clearTimeout(loadingTimer);
      loadingTimer = null;
    }
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
@import url("./style/index.scss");
</style>